package cc.cc4414.cc02.core.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cc.cc4414.cc02.system.entity.Authority;
import cc.cc4414.cc02.system.entity.User;
import cc.cc4414.cc02.system.repository.AuthorityRepository;
import cc.cc4414.cc02.system.repository.UserRepository;

/**
 * 从数据库获取认证用户的详细信息
 * 
 * @author cc 2018年6月12日
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private AuthorityRepository authorityRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userRepository.findByUsernameAndState(username, 0);
		if (user == null) {
			throw new UsernameNotFoundException("用户名不存在！");
		}
		// 给用户权限集合authorities赋值
		Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
		List<Authority> authorityList = authorityRepository.findByUserId(user.getId());
		for (Authority authority : authorityList) {
			authorities.add(new SimpleGrantedAuthority(authority.getName()));
		}
		user.setAuthorities(authorities);
		return user;
	}

}
